package cn.gbase.jiangsu.data.transfer.util;

import java.util.Map;

import javax.servlet.http.HttpSession;

import org.nutz.mvc.ActionContext;
import org.nutz.mvc.ActionFilter;
import org.nutz.mvc.Mvcs;
import org.nutz.mvc.View;
import org.nutz.mvc.view.ServerRedirectView;

/**
 * 检查用户权限的Filter.
 * 
 */
public class CheckAccessFilter implements ActionFilter {

	/**
	 * 模块名称.
	 */
	private String moduleName;

	/**
	 * 无权限时，跳转到的路径.
	 */
	private static final String FORBIDDEN_PATH = "/forbidden";

	public CheckAccessFilter(String name) {
		this.moduleName = name;
	}

	public View match(ActionContext context) {

		// 先检查是否登录了
		HttpSession session = Mvcs.getHttpSession(false);
		if (session == null || null == session.getAttribute("user")) {
			return new ServerRedirectView("/systemUser/login");
		}

		// name参数应该是这样的：平台管理.公告管理
		int index = moduleName.indexOf(".");
		if (index == -1) {
			return new ServerRedirectView(FORBIDDEN_PATH);
		}

		// 模块组的名称
		String groupName = moduleName.substring(0, index);

		// 取出模块组的权限Map
		@SuppressWarnings("unchecked")
		Map<String, Boolean> moduleGroupAccessMap = (Map<String, Boolean>) session
				.getAttribute("moduleGroupAccessMap");
		Boolean enable = moduleGroupAccessMap.get(groupName);
		if (enable == null || enable.equals(Boolean.FALSE)) {
			return new ServerRedirectView(FORBIDDEN_PATH);
		}

		// 取出模块的权限Map
		@SuppressWarnings("unchecked")
		Map<String, Boolean> moduleAccessMap = (Map<String, Boolean>) session
				.getAttribute("moduleAccessMap");
		enable = moduleAccessMap.get(moduleName);
		if (enable == null || enable.equals(Boolean.FALSE)) {
			return new ServerRedirectView(FORBIDDEN_PATH);
		}

		// 验证通过返回null
		return null;
	}

}